package cn.wl.hrm.filter;

import cn.wl.hrm.feign.client.RedisFeignClient;
import cn.wl.hrm.util.AjaxResult;
import com.alibaba.fastjson.JSON;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;


import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
public class AuthCheckFilter extends ZuulFilter {
    @Autowired
    private RedisFeignClient redisFeignClient;

    @Override
    public String filterType() {
        //类型
        return "pre";
    }

    @Override
    public int filterOrder() {
        //值越小，越先执行
        return 1;
    }

    @Override
    public boolean shouldFilter() {
        //返回true就执行下面的run方法
        //获取上下文
        RequestContext currentContext = RequestContext.getCurrentContext();
        //获取请求对象
        HttpServletRequest request = currentContext.getRequest();
        //获取URI
        String requestURI = request.getRequestURI();
        System.out.println(requestURI);
        //判断URI是否包含/login、/register、/swagger-ui.html
        if(requestURI.contains("/login") || requestURI.contains("/register") || requestURI.contains("/swagger-ui.html")){
            return false;
        }
        return true;
    }

    @Override
    public Object run() throws ZuulException {
        //登录检查
        //获取请求对象、
        RequestContext currentContext = RequestContext.getCurrentContext();
        HttpServletRequest request = currentContext.getRequest();
        //获取请求头中的token
        String token = request.getHeader("X-Token");
        //判断token是否为空
        if(StringUtils.isBlank(token)){
            authCheckError(currentContext);
        }else {
            //token不为空
            //根据token获取到缓存中对应的值
            AjaxResult ajaxResult = redisFeignClient.get(token);
            if(!ajaxResult.isSuccess() || ajaxResult.getResultObj() == null){
                //如果为false或值为空，则调用检查到错误的方法
                authCheckError(currentContext);
            }
        }
        return null;
    }

    //将检查到错误后执行的方法进行抽取
    private void authCheckError(RequestContext currentContext){
        try {
            //遇到错误，不继续执行后面的filter了
            currentContext.setSendZuulResponse(false);
            //响应给前端提示信息
            AjaxResult result = AjaxResult.me().setMessage("还未登录，请先进行登录");
            //获取响应对象
            HttpServletResponse response = currentContext.getResponse();
            //设置字符集
            response.setContentType("application/json;charset=utf-8");
            //将提示信息以json字符串的形式返还给前端
            response.getWriter().print(JSON.toJSONString(result));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
